//
//  SSWBNetworkManager+.swift
//  shanshanlol微博
//
//  Created by 叶竞泽 on 2017/1/16.
//  Copyright © 2017年 JingZe. All rights reserved.
//

import Foundation


// MARK: - 封装新浪微博的网络请求方法
extension SSWBNetworkManager {
    
    /// 加载微博数据字典数组
    ///
    /// - Parameter completion: 完成回调[list: 微博字典数组, isSuccess: 请求是否成功]
    ///   - since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ list: [[String: Any]]?, _ isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        tokenRequest(urlString: urlString, parameters: params) { (json, success) in
            
            // 服务器返回的字典数组,是按照时间倒序排列的
            // 从json中获取statuses字典数组
            guard let jsonAsObject = json as? [String: AnyObject] else {
                return
            }
            let results = jsonAsObject["statuses"] as? [[String: Any]]
            completion(results, success)
        }
    }
    
    /// 返回未读微博数量
    ///
    /// - Parameter completion: 回调
    func unreadCount(completion: @escaping (_ count: Int) -> ()) {
        
        guard let uidNew = userAccount.uid else {
            print("没有uid,无法获取数据")
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        
        let params = ["uid": uidNew]
        
        tokenRequest(urlString: urlString, parameters: params) { (json, success) in
            
            let dict = json as? [String : AnyObject]
            // 从json中获取未读数量字典
            completion(dict?["status"] as? Int ?? 0)
        }
    }
    
}

// MARK: - 发布微博
extension SSWBNetworkManager {
    
    
    /// 发布微博方法
    ///
    /// - Parameters:
    ///   - status: 要发布的微博文字
    ///   - image: 要发布的微博图片,为nil时,就是发布纯文本
    ///   - completion: 回调方法
    func postStatus(status: String, image: UIImage?, completion: @escaping (_ result: [String: Any]?, _ success: Bool) -> ()) -> () {
        
        // 1.URL
        let urlString: String
        
        if image == nil {
            urlString = "https://api.weibo.com/2/statuses/update.json"
        } else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        // 2.参数
        let params = ["status": status]
        
        // 3.发起带参数的tokenRequest
        // 如果图像不为空,需要设置name和data
        var name: String?
        var data: Data?
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        tokenRequest(method: .POST, urlString: urlString, parameters: params, name: name, data: data) { (json, success) in
            // 服务器返回的字典数组,是按照时间倒序排列的
            // 从json中获取statuses字典数组
            completion(json as? [String: Any], success)
        }
    }
    
}

// MARK: - 用户信息
extension SSWBNetworkManager {
    
    /// 加载当前用户信息,用户登录后立即执行
    func loadUserInfo(completion: @escaping (_ dict: [String: Any]) -> ()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid": uid]
        
        // 发起网络请求
        tokenRequest(method: .GET, urlString: urlString, parameters: params) { (json, isSuccess) in
    
            // 完成回调
            completion((json as? [String: Any]) ?? [:])
        }
    }
}

// MARK: - OAuth相关方法
extension SSWBNetworkManager {
    
    /// 加载accesstoken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 完成回调
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": WBAppKey, "client_secret": WBAppSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": WBRedirect_url] 
        
        // 发起网络请求
        request(method: .POST, urlString: urlString, parameters: params) { (json, isSuccess) in
            
            self.userAccount.yy_modelSet(with: json as? [String: Any] ?? [:])
            
            
            
            // 加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                
                // 使用用户信息地点设置用户信息,用户昵称和用户头像地址
                self.userAccount.yy_modelSet(with: dict)
                // 保存到沙盒
                self.userAccount.saveAccount()
                // 完成回调
                completion(isSuccess)
                print(self.userAccount)
            })
        }
    }
}
